package com.xbongbong.paas.script.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.service.PaasProcessTemplateService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.ProcessDTO;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 流程相关脚本，
 *
 * @author lee
 * @since V1.0
 * @date 2019/7/09 10:42
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/process")
public class ProcessLinkController {

    private static final Logger LOG = LoggerFactory.getLogger(ProcessLinkController.class);

    @Resource
    PaasProcessTemplateService paasProcessTemplateService;
    @Resource
    PaasProcessDataModel paasProcessDataModel;
    @Resource
    PaasFormExplainModel paasFormExplainModel;

    /**
     *
     * @throws Exception
     */
    @RequestMapping(value = "/initProcess", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initDemo(@RequestBody @Valid ProcessDTO processDTO, BindingResult br) {
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                paasProcessTemplateService.initProcessNode(processDTO);
                response = new XbbResponse<>(new ScriptVO());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);

    }

    /**
     * 奥琦玮专用  dingbc056cd6656b2080
     * @param processDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/fixPaymentSheetData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixPaymentSheetData(@RequestBody @Valid ProcessDTO processDTO, BindingResult br) throws XbbException {
        for (String corpid : processDTO.getCorpidList()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("businessType", XbbRefTypeEnum.PAYMENT_SHEET.getCode());
            params.put("del", 0);
            params.put("corpid", corpid);
            //params.put("flowStatusIn", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), PaymentSheetEnum.PAY_METHOD.getAttr());
            List<ItemPoJo> itemPoJos = explainMap.get(PaymentSheetEnum.PAY_METHOD.getAttr()).getItems();
            List<PaasProcessDataEntity> paasProcessDataList = paasProcessDataModel.list(params);
            List<PaasProcessDataEntity> updateDataList = new ArrayList<>();
            for (PaasProcessDataEntity paasProcessDataEntity : paasProcessDataList) {
                JSONObject jsonObject = JSONObject.parseObject(paasProcessDataEntity.getData());
                String text_3 = jsonObject.getString(PaymentSheetEnum.PAY_METHOD.getAttr());
                if (StringUtil.isNotEmpty(text_3)) {
                    for (int i = 0; i < itemPoJos.size(); i++) {
                        ItemPoJo itemPoJo = itemPoJos.get(i);
                        String value = "\"" + itemPoJo.getValue().toString() + "\"";
                        if (text_3.contains(value)) {
                            jsonObject.put(PaymentSheetEnum.PAY_METHOD.getAttr(), itemPoJo.getValue().toString());
                            paasProcessDataEntity.setData(jsonObject.toJSONString());
                            updateDataList.add(paasProcessDataEntity);
                            break;
                        }
                        if (i == itemPoJos.size() - 1 && text_3.length() > 4) {
                            jsonObject.remove(PaymentSheetEnum.PAY_METHOD.getAttr());
                            paasProcessDataEntity.setData(jsonObject.toJSONString());
                            updateDataList.add(paasProcessDataEntity);
                        }
                    }
                }
            }
            if (!updateDataList.isEmpty()) {
                paasProcessDataModel.updateBatch(updateDataList, corpid);
                LOG.error("=====script" + updateDataList.size());
            }
        }
        return null;
    }


}
